#!/bin/bash
########################################################################
# script name:  scp_to
# Used for:     scp files to remote targets
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2011/08/18    0.1     MDUMONT         initial
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

scp files to remote targets

OPTIONS:
   -h               Comma seperated list of hosts, or ALL
   -s               Source file
   -d               Destination file (can be [.] for home dir)

Ex.:
$0 -h saprmt02 -s /tmp/test -d /tmp/test
$0 -h saprmt02,saprmt01 -s /etc/profile -d .
$0 -h ALL -s /etc/profile -d /tmp/profile

STOP
}
#######################################
# Variables and environnement
#######################################
BAENV=$(diname $0)/loadenv.sh
if [ -f $BAENV ]; then . $BAENV; else echo "No env library ($BAENV)"; exit 1; fi
#######################################
# Get parameters
#######################################
while getopts h:s:d: OPTION
do
        case $OPTION in
        h)
                HOSTS=$(echo $OPTARG | tr [:upper:] [:lower:] | sed 's/,/ /g')
                ;;
        s)
                SOURCE=$OPTARG
                ;;
        d)
                DESTINATION=$OPTARG
                ;;
        \?)
                usage
                exit 1
                ;;
        *)
                usage
                exit 1
                ;;
        esac
done
if [ $OPTIND = 1 ]; then usage; exit 1; fi
if [ -z "$HOSTS" ]; then echo "Specify a host..."; usage; exit 1; fi
if [ ! -f "$SOURCE" ]; then echo "Source file not specified or not existing..."; usage; exit 1; fi
if [ -z "$DESTINATION" ]; then echo "Specify a destination file..."; usage; exit 1; fi
#######################################
# Functions
#######################################
function check_source {
	TMPSOURCE=$1
	if [ ! -f "$TMPSOURCE" ]; then echo "$0: ERROR: File source $TMPSOURCE not found" >&2; exit 1; fi
}
#######################################
# MAIN
#######################################
NEWHOSTLIST=$(checkhost $HOSTS | grep -v Verifying)
#check_source $SOURCE
for HOSTNAME in $NEWHOSTLIST
do
	echo -e "SCP file $SOURCE to $HOSTNAME:$DESTINATION ... \c"
	scp -q $SOURCE $HOSTNAME:$DESTINATION 2>/dev/null
	RC=$?
	if [ $RC != 0 ]; then echo FAILED; else echo ok; fi
done
#######################################
exit 0
